package com.aoeai.rg.language.view_model

import android.app.Application
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.viewModelScope
import com.aoeai.rg.language.data.repository.LanguageRepository
import com.aoeai.rg.language.manager.LanguageManager
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.stateIn
import kotlinx.coroutines.launch

class LanguageViewModel(application: Application) : AndroidViewModel(application) {
    private val repository = LanguageRepository(application)
    val availableLanguages = repository.availableLanguages

    val currentLanguageCode = repository.currentLanguageCode
        .stateIn(viewModelScope, SharingStarted.WhileSubscribed(), "")

    init {
        viewModelScope.launch {
            repository.currentLanguageCode.collect { code ->
                LanguageManager.updateLanguage(application,code)
            }
        }
    }

    fun setLanguage(languageCode: String) {
        viewModelScope.launch {
            repository.setLanguage(languageCode)
            LanguageManager.updateLanguage(getApplication(),languageCode)
        }
    }
}